package com.example.config;

import com.alibaba.fastjson.JSONArray;
import com.example.mapper.AlarmMapper;
import com.example.pojo.alarm.messageRemind;
import com.example.pojo.subscription.subscriptionContent;
import com.example.pojo.subscription.subscriptionMessage;
import com.example.pojo.subscription.userSubscription;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;


/***
 *
 * 给broker发送信息
 * 2022--526
 * by liming
 *
 */



@Component
@Configuration
public class ServiceMQTT {

    public static final String HOST = "tcp://iot.situos.cn:1883";
    @Value("${web.mqtt}")
     private String mqtt;
    @Value("${web.mqtt}")
    private static  String mqtts;
//   private String ServiceID = "Drools发送报警XAJD";
   private String ServiceID = "Drools发送报警"+mqtts;
    private   String topic="ws2";
    private MqttClient client;
    private MqttTopic mqttTopic;
    private MqttConnectOptions options;
    private String user = "yunsitu";
    private String password = "Yst123@456";

    private MqttMessage message;
    @Autowired
    private AlarmMapper alarmMapper;
    @Autowired
    private  ItemClientFeign itemClientFeign;

    public ServiceMQTT() throws MqttException {
        //创建连接
        client = new MqttClient(HOST,ServiceID,new MemoryPersistence());
        options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setKeepAliveInterval(20);
        options.setConnectionTimeout(50);
        options.setUserName(user);
        options.setPassword(password.toCharArray());
        message = new MqttMessage();
    }

    public void getConnect(){
        try {
            client.setCallback(new PublishCallBack());
            client.connect(options);
            mqttTopic = client.getTopic(topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void publish(MqttTopic topic, MqttMessage message) throws MqttException {
        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();
        System.out.println("消息推送的状态--->"+token.isComplete());
    }


    // Scanner input = new Scanner(System.in);

    //System.out.print("请输入消息的主题：");

    public void   alarm(HashMap<String, Object> alarm) throws MqttException {
        ServiceMQTT service = new ServiceMQTT();
        service.topic = topic;
//
      //  System.out.print("请输入消息的内容：");
       // String messageVal = alarm;
        //Map<String, Object> map = new HashMap<>();
        alarm.put("drools",mqtt); // 广西大学
        alarm.put("pronumber",itemClientFeign.getProjectCode()); // 查询项目编码
    // alarm.put("drools","cs"); // 西交项目
       // alarm.put("drools","cf"); //赤峰项目


//        alarmMapper.addsubscriptionMessage();


        service.getConnect();

        service.message.setQos(0);
        service.message.setRetained(true);
        service.message.setPayload(JSONArray.toJSONString(alarm).getBytes());

        service.publish(service.mqttTopic,service.message);
    //    try {
            this.subMessage(alarm);
//        }
//        catch (Exception e) {
//
//        }
        System.out.println("消息的保持状态："+service.message.isRetained());
    }


    public  void  subMessage(HashMap<String, Object> alarm)  {
        messageRemind messageRemind = (messageRemind) alarm.get("data");

        String Contenttype = null;
        String firstValue = null;
        if (messageRemind.getOrderType().contains("报警")) {

            Contenttype = "报警提醒";
            firstValue = "您有一个设备报警提醒，请尽快处理";
        } else if (messageRemind.getOrderType().contains("离线")) {

            Contenttype = "离线提醒";
            firstValue = "您有一个设备离线提醒，请尽快处理";
        } else if (messageRemind.getOrderType().contains("预警")) {

            Contenttype = "预警提醒";
            firstValue = "您有一个设备预警提醒，请尽快处理";
        } else if (messageRemind.getOrderType().contains("故障")) {

            Contenttype = "故障提醒";
            firstValue = "您有一个设备故障提醒，请尽快处理";
        } else if (messageRemind.getOrderType().contains("保养")) {
            Contenttype = "保养提醒";
            firstValue = "您有一个设备维保提提醒，请尽快处理";
        } else if (messageRemind.getOrderType().contains("环境") || messageRemind.getOrderType().contains("气体")) {
            Contenttype = "环境安全";
            firstValue = "您有一个环境安全提醒，请尽快处理";
        }
        String subsystemBelong = messageRemind.getSubsystemBelong();
        String systemBelong = messageRemind.getSystemBelong();
        String storey = messageRemind.getLocation();
        if ((messageRemind.getAlarmType().equals("alarm") || messageRemind.getAlarmType().equals("maintain"))
                && (!messageRemind.getOrderType().contains("环境") && !messageRemind.getOrderType().contains("气体") )) {
            //查询是否管理此报警
            if (StringUtils.isNotBlank(subsystemBelong) && StringUtils.isNotBlank(systemBelong)) {
                //查寻设备
                List<userSubscription> userSubscriptions = alarmMapper.selectDevicebydeviceSafety(subsystemBelong, systemBelong);
                if (userSubscriptions.size() != 0) {
                    for (userSubscription  userSubscription: userSubscriptions) {
                        subscriptionContent subscriptionContent = alarmMapper.selectContentbysubscribers( userSubscription.getId(), Contenttype);
                        if (subscriptionContent.wechat) {
                            this.wx(messageRemind, Contenttype,userSubscription.getSubscribers());
                        }
                    }
//                } else {
//                    //如果没有人管理设备 查找这个设备所在房间
//                    if (storey!=null){
//                        List<userSubscription> userSpaces = alarmMapper.selectSpacebystorey(storey.split(" ")[0]);
//                        Contenttype = "从属设备";
//                        for (userSubscription  userSubscription: userSpaces) {
//                            subscriptionContent subscriptionContent = alarmMapper.selectContentbysubscribers( userSubscription.getId(), Contenttype);
//                            if (subscriptionContent.wechat) {
//                                this.wx(messageRemind, Contenttype,userSubscription.getSubscribers());
//                            }
//                        }
//                    }
//
//                }
            }else {
                List<userSubscription> selectall = alarmMapper.selectall( );
                for (userSubscription userSubscription : selectall) {

                    //查询是否发生警报
                    subscriptionContent subscriptionContent = alarmMapper.selectContentbysubscribers(
                            userSubscription.getId(), "气瓶压力");
                    if (subscriptionContent != null && subscriptionContent.wechat) {

                        this.wx(messageRemind, "气瓶压力", userSubscription.getSubscribers());
                    }
                }
            }
        }} else {
            List<userSubscription> userSpaces = new ArrayList<userSubscription>();
            //因最开始只用房间名 房间名可能有重复所以加一个判断 使以前改不了的项目也正常使用
            userSpaces = alarmMapper.selectSpacebystorey(storey);
            if (userSpaces.size()==0) {
                userSpaces = alarmMapper.selectSpacebystorey(storey.split(" ")[0]);
            }
//            List<userSubscription> userSpaces = alarmMapper.selectSpacebystorey(storey.split(" ")[0]);
            for (userSubscription  userSubscription: userSpaces) {
                System.out.println(userSubscription.getSubscribers());
                subscriptionContent subscriptionContent = alarmMapper.selectContentbysubscribers( userSubscription.getId(), Contenttype);
                if (subscriptionContent.wechat) {
                    this.wx(messageRemind, Contenttype,userSubscription.getSubscribers());
                }
            }
        }}


    public void wx(messageRemind messageRemind,String Contenttype,String subscribers) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        subscriptionMessage subsequentMessage = new subscriptionMessage();
        String format = sdf.format(new Date());
        subsequentMessage.setMessageDate(format);

        if (messageRemind.getOrderType().contains("环境") || messageRemind.getOrderType().contains("气体") ){
            subsequentMessage.setMessageType("环境安全");
            subsequentMessage.setDeviceArea(messageRemind.getLocation());
        }else {
            subsequentMessage.setMessageType("设备安全");
            subsequentMessage.setDeviceArea(messageRemind.getDevLocation());
            subsequentMessage.setDeviceName(messageRemind.getDevName());
            subsequentMessage.setDeviceNumber(messageRemind.getDevNumber());
        }
        subsequentMessage.setAlarmType(messageRemind.getOrderType());


        subsequentMessage.setMessageContent(messageRemind.getDescription());
//        subsequentMessage.setStatusDescription(informatin);

        subsequentMessage.setSubscribers(subscribers);


        subsequentMessage.setAlarmGrade(messageRemind.getFaultLevel());
        subsequentMessage.setAlarmTime(sdf.format(messageRemind.getLastrecialamtime()));
        subsequentMessage.setIsNew(1);
        subsequentMessage.setMessageState("发送成功");

        alarmMapper.addsubscriptionMessage(subsequentMessage);
    }
}


